const express = require('express');
const router = express.Router();
const mysql = require('mysql')
const db = require('../../sql/db')
const $sql = require('../../sql/sqlMap')
const pathLib = require('path');
const fs = require('fs');
const multer = require('multer');

let storage = multer.diskStorage({
    //表示图片上传后将保存的路径地址
    //设置上传文件路径后,uploads文件夹将会在服务器相对应的路径下创建
    //由于服务器文件夹的权限不同,如果自动创建失败,可以手动在相应的路径下手动创建文件夹
    destination: function (req, file, cb) {
        cb(null, './public/imgs/feedback')
    },
    //给上传的文件进行重命名,获取添加后缀名
    filename: function (req, file, cb) {

        //为了防止小概率文件名相同,将文件名改为时间戳＋后缀
        let suffix = '';
        for (let i = file.originalname.length - 1; i >= 0; i--) {
            suffix += file.originalname[i];
            if (file.originalname[i] === '.') break;
        }
        let reSuffix = suffix.split('').reverse().join('');
        cb(null, '' + Date.now() + reSuffix); // cb(null,'创建文件的名字')

    }
});
let upload = multer({storage: storage});

const connection = mysql.createConnection(db.mysql);
connection.connect();
const sql = $sql.user.applyCredit;

router.post('/:id', upload.array('file', 12), (req, res, next) => {
    console.log(11)
    // console.log(req.fields)
    console.log(req.body);
    let paths = '';
    for (let i = 0; i < req.files.length; i++) {
        paths += req.files[i].path;
    }
    console.log(paths)
    paths = paths.replace('public', '');
    console.log(paths)
    connection.query(sql, [req.params.id, paths, req.body.reason, req.body.creditNumber], (err, result) => {
        if (err) {
            console.log(err)
            return
        }
        res.json({
            status: '0',
            msg: '发送申请成功',
            result: result
        })
    })
});

module.exports = router;
